package com.home.task;

import com.home.base.util.FetchHaomaUtil;
import com.home.base.util.FetchLtUtil;
import com.home.biz.HaomaBiz;
import com.home.biz.JobLogBiz;
import com.home.biz.LtPhoneBiz;
import com.home.config.InitDataConfig;
import com.home.entity.JobLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author ：chenxf
 * @date ：Created in 2020/6/10 13:40
 * @description：
 * @modified By：
 * @version: $
 */
@Slf4j
@Component
public class SiteFetchTask {
    @Autowired
    JobLogBiz logBiz;

    @Async
    public void activityTask(HaomaBiz activityBiz, String activiName, String sNum, String eNum, String tNum){
        Instant begin = Instant.now();
        InitDataConfig.setFetchStatus(true);
        logBiz.insertSelective(JobLog.builder().notes(activiName+" 线程数"+tNum+" "+sNum+ "-"+eNum+"开始采集").build());
        try {

            List<Future<String>> resultList = new ArrayList<Future<String>>();
            ExecutorService executorService = Executors.newFixedThreadPool(Integer.valueOf(tNum));
            int length=sNum.length();
            int fetchNum=Integer.valueOf(sNum);
            while (fetchNum<=Integer.valueOf(eNum)){
                //采集
                Future<String > future;

                    future = executorService.submit(new FetchHaomaUtil(activityBiz,activiName,String.format("%"+length+"d",fetchNum).replace(" ", "0")));


                // 将任务执行结果存储到List中
                resultList.add(future);
                // phoneBiz.saveList(provInfo.getName(),parent.getName(),"移动花卡宝藏版", FetchUtil.sjData(data.replace("#PROV",provInfo.getProvcode().toString()).replace("#KEY",String.format("%4d",10).replace(" ", "0")).replace("#CITY",provInfo.getPid().toString())));

                fetchNum++;
            }
            for (Future<String> fs : resultList) {
                try {
                    log.debug("采集结果："+fs.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            logBiz.insertSelective(JobLog.builder().notes(activiName+" 线程数"+tNum+" "+sNum+ "-"+eNum+"采集异常"+e.getMessage()).build());
            InitDataConfig.setFetchStatus(false);
            return;
        }
        Instant end = Instant.now();
        InitDataConfig.setFetchStatus(false);
        logBiz.insertSelective(JobLog.builder().notes(activiName+" 线程数"+tNum+" "+sNum+ "-"+eNum+"采集完成。耗时:"+ Duration.between(begin, end).toMinutes()+"分钟 采集共："+activityBiz.counts()+"个手机号码").build());
    }
}
